package com.dji.sample.manage.controller;

import com.alibaba.fastjson2.JSONObject;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.manage.model.dto.StreamDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author yjt
 * @date 2023-02-08
 * @description:
 */
@RestController
@RequestMapping("/manager")
public class LiveController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/live")
    public ResponseResult<?> getLiveInfo(@RequestParam(required = false) String deviceSn) {
        if (StringUtils.hasText(deviceSn)) {
            Set<String> objects = redisTemplate.keys(getLiveInfoKey(deviceSn));
            if (objects == null || objects.isEmpty()) {
                return ResponseResult.error("未查询到直播信息");
            }
            for (String object : objects) {
                Object obj = redisTemplate.opsForValue().get(object);
                if(obj!=null){
                    StreamDTO streamDTO = JSONObject.parseObject(String.valueOf(obj),StreamDTO.class);
                    return ResponseResult.success(streamDTO);
                }
            }
            return ResponseResult.error("未查询到直播信息");
        }
        Set<String> objects = redisTemplate.keys(getLiveInfoAllKey());
        if(objects==null || objects.isEmpty()){
            return ResponseResult.error("未查询到直播信息");
        }
        List<StreamDTO> list = new ArrayList<>();
        for (String object : objects) {
            Object obj = redisTemplate.opsForValue().get(object);
            if(obj!=null){
                StreamDTO streamDTO = JSONObject.parseObject(String.valueOf(obj),StreamDTO.class);
                list.add(streamDTO);
            }
        }
        return ResponseResult.success(list);
    }

    public static String getLiveInfoKey(String app) {
        return String.format("live:room:%s:*", app);
    }

    public static String getLiveInfoAllKey() {
        return "live:room:*";
    }


}
